package com.ybb.vue.common.security;

import com.ybb.vue.common.exception.UserCountLockException;
import com.ybb.vue.entity.SysUser;
import com.ybb.vue.service.Impl.SysUserServieceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义UserDetailsService
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserServieceImpl userServiece;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userServiece.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if (sysUser.getStatus().equals("1")) {
            throw new UserCountLockException("该账号已被封禁，请联系管理员解封！");
        }
        return new org.springframework.security.core.userdetails.User(sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(String userId) {
        String authority =  userServiece.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
